// 按钮组显示隐藏切换按钮
const toggle = this.pageObj.getApiWidgetByAliasName('toggle');
// 弹窗 - 记录动态、一键会议、下发任务、协同会商、信息上报等。
const process = this.pageObj.getApiWidgetByAliasName('modal-process');
// Dev 系统环境变量
const prefix = this.pageObj.getVariables().find(v => v.name === "environmentType")?.value;
// 三维组件
const widgetsGis = this.getApiPage().getApiWidgetByAliasName('三维组件')?.widgetObj;
// 路由参数
let params = this.pageObj.getVariables().find(v => v.name === "screen_params")?.value;
// 弹窗中的默认配置数据
const configs = process?.widgetObj.configs();
const Modal = process?.widgetObj.getModal();

if (params) {
    try {
        params = JSON.parse(params)
    } catch (e) {
        const { dataSource } = this.getApiPage().getApiWidgetByAliasName('judge-content')?.widgetObj._option || {};
        params = dataSource;
        console.error(e)
    }
}

// HTTP POST
const requestPost = (url, body, headers = {}) => {
    return fetch(url, {
        method: 'POST',
        headers: { "Content-Type": "application/json", ...headers },
        body: typeof body === 'object' ? JSON.stringify(body) : body,
    }).then(res => res.json())
};
// HTTP GET
const requestGet = (url) => {
    const headers = { "Content-Type": "application/json" };
    return fetch(url, { headers }).then(res => res.json())
};
console.log($event, configs);

// 一键会议
function callAllMembers () {
    const artemis = widgetsGis?.artemis;

    if (artemis && params?.id) {
        const headers = { "Content-type": "application/x-www-form-urlencoded" };
        const body = 'eventId=' + params.id;
        requestPost(`/${prefix}SummaryAssessmentSV/emergencyHandle/convergedCommunication`, body, headers).then(res => {
            if (res.success) {
                res.result.forEach(data => {
                    data.userId = data.communicationAccount;
                    data.username = data.communicationName;
                    artemis.addMember(data);
                });

                artemis.createVideoMeeting();
            }
        })
    }
}

// 录像回放
const recordPlay = () => {
    // 回放组件
    const $playback = this.getApiPage().getApiWidgetByAliasName('playback');
    // 事件明细数据
    const { eventDetails } = params;

    if (eventDetails && Object.keys(eventDetails).length > 0) {
        const info = JSON.parse(eventDetails);
        widgetsGis.gisMap.setModalType('NONE');
        console.log('info', info);
        if (info.jpbPath) {
            $playback.widgetObj.setData([{ data: info.jpbPath }]);
            $playback.showWidget();
            $playback.widgetObj.render();
        } else {
            $playback.hideWidget();
            window.layer.msg('暂无录像回放')
        }
    } else {
        $playback.hideWidget();
        window.layer.msg('暂无录像回放')
    }
}

// 播放实时画面
const playing = () => {
    const { sourceDeviceId } = params;

    console.log('detailForm', detailForm);
    widgetsGis.gisMap.setModalType('NONE');

    if (sourceDeviceId) {
        const search = `?equipmentCode=${sourceDeviceId}`;
        // 打开实时视频
        requestGet(`/${prefix}Basics/basics-main/system/equipmentObject/listDetailByEquipmentCode${search}`)
            .then(({ success, result } = {}) => {
                console.log({ success, result });
                if (success && result) {
                    const { rows } = result;
                    const data = rows[0]?.equipmentConfig?.gbVideoConfig;
                    var host = this.getApiPage().getVariables().find(x => x.name == "stream_url").value;
                    widgetsGis.sullivan.close();
                    if (data && data.sipUser && data.videoChannelId) {
                        widgetsGis.sullivan.initial();
                        widgetsGis.sullivan.addPlayer(`${host}/api/v1/stream/rtc/play`, `${data.sipUser}/${data.videoChannelId}`)
                    } else {
                        window.layer?.msg('暂无设备号/通道号')
                    }
                }
            })
    }else {
        widgetsGis?.sullivan?.close();
        window.layer.msg('未关联摄像头');
    }
}

// 处理表单 - 详情
const executeForm = (detail) => {
    const $form     = this.getApiPage().getApiWidgetByAliasName('change-form');
    let info;
    try {
        if(dataSource.eventDetails) info = JSON.parse(dataSource.eventDetails)
    } catch (e) {
        console.error(e)
    }

    $form.widgetObj._option.dataSource = {
        ...detail,
        eventPoint: detail.pointId,
        thumbnailPath: info?.thumbnailPath,
        jpbPath: info?.jpbPath,
    };
};


let config;
let style = { width: 600, height: 400 };
switch($event) {
    case '记录动态':
        config = configs['记录动态'](2);
        break;
    case '解除演练':
        config = configs['自定义内容']('提示：是否确定解除演练');
        break;
    case '结束演练':
        config = configs['自定义内容']('提示：是否确定结束演练');
        break;
    case '一键会议':
        callAllMembers ();
        break;
    case '实时画面':
        playing ();
        break;
    case '录像回放':
        recordPlay ();
        break;
    case '变更演练':
        this.pageObj.getApiWidgetByAliasName('toggle')?.hideWidget();
        // 详情 - 隐藏
        this.pageObj.getApiWidgetsByClassName('event-operate')?.forEach(v => v.hideWidget());
        // 演练执行 - 隐藏
        this.pageObj.getApiWidgetsByClassName('演练执行')?.forEach(v => v.hideWidget());
        // 编辑 - 显示
        this.pageObj.getApiWidgetsByClassName('change')?.forEach(v => v.showWidget());
        // 演练概要 - 显示
        this.pageObj.getApiWidgetsByClassName('演练概要')?.forEach(v => v.showWidget());
        executeForm(params);
        break;
    default:
        config = configs[$event](2);
        if ($event === '协同会商') {
            style.width = 650;
            style.height = 450;
        } else {
            style.height = 500;
        }
}

if (config) {
    const url = new URLSearchParams(window.location.href);
    const personDetail = JSON.parse(url && url.get('personDetail') || '{}');
    const taskTypeEnum = { 信息发布: '1', 信息上报: '2', 下发任务: '10' };
    const defaultData = {
        ...params,
        eventId: params.id,
        eventTitle: params.drillName,

        taskTypeId: taskTypeEnum[$event],
        taskTypeName: $event,
        // 下发部门
        taskIssuDepart: personDetail.deptCode,
        taskIssuDepartName: personDetail.deptName,

        // 下发人
        taskIssuer: personDetail.id,
        taskIssuerName: personDetail.personName,

        // 记录人
        takenotesPersonName: personDetail.personName,
        takenotesPersonId: personDetail.id,
        progress: 2,
    }
    Modal.type = $event;
    process?.widgetObj.renderModal(config, defaultData);
    process?.widgetObj.show(style);
}

toggle?.widgetObj.toggle();

